var roleId;
var join_user_win;
var join_user_grid,join_user_store,search_user_store;

Ext.define('userModel', {
    extend: 'Ext.data.Model',
    fields: [
        'user_id','user_name','user_realname'
    ],
    idProperty: 'user_id'
});

/**
 * 加载可被授权的有效用户
 */
search_user_store = Ext.create('Ext.data.Store', {
    id:'data_user_roles',
    model: 'userModel',
    proxy: {
        type: 'ajax',
        method: 'GET',
        url: '/admin_user/list?status=0',
        reader: {
           type: 'json',
           root: 'data',
           totalProperty: 'count'
        },
        simpleSortMode: true,
		listeners:{
            'exception':function( theproxy, response, operation, options ){
            	var data = eval("("+response.responseText+")");
            	if(!data.success){
            		Ext.Msg.alert('信息提示',data.msg);
            	} else {
            		Ext.Msg.alert("信息提示","系统忙，请稍候再试");
            	}
            }
        }
    }
});

/**
 * 已经加入当前角色的用户
 */
join_user_store = Ext.create('Ext.data.Store', {
    id:'data_user_roles',
    pageSize: 20,
    model: 'userModel',
    remoteSort: true,
    proxy: {
        type: 'ajax',
        method: 'GET',
        url: '/role/users',
        reader: {
           type: 'json',
           root: 'data',
           totalProperty: 'count'
        },
        simpleSortMode: true,
		listeners:{
            'exception':function( theproxy, response, operation, options ){
            	var data = eval("("+response.responseText+")");
            	if(!data.success){
            		Ext.Msg.alert('信息提示',data.msg);
            	} else {
            		Ext.Msg.alert("信息提示","系统忙，请稍候再试");
            	}
            }
        }
    }
});

join_user_grid = Ext.create('Ext.grid.Panel', {
    id:'my_grid',
    store: join_user_store,
    loadMask: true,
    region: 'center',
    selModel: Ext.create('Ext.selection.CheckboxModel'),
    columns: [
        {
            text: "用户ID",
            dataIndex: 'user_id'
        },
        {
            text: '用户登陆名',
            dataIndex: 'user_name',
            width : 180

        },
        {
            text: '用户姓名',
            dataIndex: 'user_realname',
            width : 180

        }
    ],
    bbar: Ext.create('Ext.PagingToolbar', {
        store: join_user_store,
        displayInfo: true,
        displayMsg: '当前显示  {0} - {1} 共  {2} 条',
        emptyMsg: "没有数据显示！",
        beforePageText: "页码",
		afterPageText: "共 {0} 页",
		firstText:"首页",
		lastText:"末页",
		nextText:"下一页",
		prevText:"上一页",
		refreshText:"刷新"
    }),
    tbar: [
        {
        	xtype:'combobox',
        	//hideTrigger:true,
        	triggerAction:'all',
        	id:'combo_user',
        	fieldLabel:'选择待授权用户',
            emptyText:'请输入姓名搜索/选择',
        	maxLength:50,
        	store:search_user_store,
        	queryMode:'remote',
            queryParam: 'user_name',
            minChars: 1,
            editable:true,
        	labelWidth:110,
        	displayField: 'user_realname',
            valueField: 'user_id',
        	listeners:{
        		'beforequery' : function(e) {
        			var combo = e.combo;   
        			if(!e.forceAll){   
        				var value = e.query;   
        				combo.store.filterBy(function(record,id){   
        					var text = record.get(combo.displayField); 
        					//combo.setValue(record.get('userid'));
        					//combo.setValue(record.get(combo.valueField));
        					return (text.indexOf(value)!=-1);   
        				});
        				combo.expand();   
        				return false;   
        			}
        		}
        	}
        },
		{
		    icon : '../../img/search.png',
		    text: "查  询",
		    hidden:true,
		    handler: function(){searchHandler()}
		},
		{
			icon : '../../img/drop-add.png',
			text: "加  入",
			handler: function(){joinHandler()}
		},
		{
			icon : '../../img/delete_list.png',
			text: "移  除",
			handler: function(){rmHandler()}
		},
		{
			icon : '../../img/close.png',
			text: "关  闭",
			handler: function(){
				//join_user_win.hide();
				//清除search_user_store的roleId参数
				//join_user_store.clearListeners();
				//刷新iframe
				join_user_win.hide();
				window.location.reload();
			}
		}
    ]
});

function searchHandler(){
}

function joinHandler(){
	var combo_user = Ext.getCmp('combo_user');
	if(combo_user.getValue()==null || combo_user.getValue()==''){
		Ext.Msg.alert('信息提示','请选择用户！');
		return;
	}
	var user_id = combo_user.getValue();
	//判断user_id是否存在当前角色用户列表中
	join_user_store.each(function(record,index,size){
		if(record.get('user_id') == user_id){
			Ext.Msg.alert('信息提示','该用户已拥有当前角色，无需重复加入！');
			user_id='';
		}
	});
	if(user_id=='')
		return;
	//发起请求，将选择的用户加入当前角色
	Ext.Ajax.request({
        url: '/role/adduser?role_id='+roleId+"&user_id="+user_id,
        method : 'POST',
        success: function(response, opts) {
            var data = eval("("+response.responseText+")");
            Ext.Msg.alert('信息提示',data.msg);
            join_user_store.reload();
        },
        failure: function(response, opts) {
        	var data = eval("("+response.responseText+")");
        	if(!data.success){
        		Ext.Msg.alert('信息提示',data.msg);
        	} else {
        		Ext.Msg.alert("信息提示","系统忙，请稍候再试");
        	}
        }
    });
}

function rmHandler(){
	var records = join_user_grid.getSelectionModel().getSelection();
	if(records.length == 0){
		Ext.Msg.alert("信息提示","请选择需要移除的用户！");
		return;
	}
	Ext.MessageBox.confirm('信息提示','确认移除吗？',function(val){
		if(val == 'yes'){
	    	Ext.Ajax.request({
	            url: '/role/rmUserInRole?user_id='+records[0].get("user_id")+"&role_id="+roleId,
	            method : 'POST',
	            success: function(response, opts) {
	                var data = eval("("+response.responseText+")");
	                Ext.Msg.alert('信息提示',data.msg);
	                join_user_store.reload();
	            },
	            failure: function(response, opts) {
	            	var data = eval("("+response.responseText+")");
	            	if(!data.success){
	            		Ext.Msg.alert('信息提示',data.msg);
	            	} else {
	            		Ext.Msg.alert("信息提示","系统忙，请稍候再试");
	            	}
	            }
	        });
		}
	});
}

function join_user(role_id, role_name){
	if(!join_user_win){
		join_user_win = Ext.create('Ext.Window', {
    		title: '已授权【'+role_name+'】的用户列表',
    		width: 700,
    		height: 550,
    		bodyPadding: '0 0 0',
    		constrainHeader: true,
    		closeAction:'hide',
    		layout: 'fit',
    		items: join_user_grid,
    		listeners:{
    			'hide':function(){
    				window.location.reload();
    				//join_user_win.hide();
    			}
    		}
    	});
	}
	join_user_win.show();
	roleId = role_id;
	search_user_store.load();
	join_user_store.loadPage(1,{params:{role_id:role_id}});
	//设置roleId为join_user_store的base参数，翻页时也需要获取roleId
	join_user_store.on('beforeload', function(store, operation, eOpts) {
		operation.params = {role_id:role_id};
	}, this);
}
